package com.cvte.sunkit.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.util.Log
import android.util.TypedValue
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.cvte.sunkit.R
import com.cvte.sunkit.service.FloatingService
import com.cvte.sunkit.ui.base.BaseActivity
import com.cvte.sunkit.utils.ActivityCollector
import com.cvte.sunkit.manage.DropboxLogcatManager
import com.cvte.sunkit.utils.PopTipUtils
import com.kongzue.dialogx.dialogs.BottomMenu
import com.kongzue.dialogx.interfaces.OnMenuItemSelectListener


@Suppress("DEPRECATION")
class MainActivity : BaseActivity() {
    private lateinit var mBtnOpenFloatWindow: ImageView
    private lateinit var mBtnQuitApp: ImageView
    private lateinit var mBtnDropbox: ImageView



    private val mSingleSelectMenuText = mutableListOf("自开机以来", "3天以来", "2天以来", "一天内")
    private val mSingleSelectDay = mutableListOf(0L, 3L * TIME_DAY, 2L * TIME_DAY, 1L * TIME_DAY)


    private val REQUEST_MEDIA_PROJECTION = 1
    private var mediaProjectionManager: MediaProjectionManager? = null

    companion object {
        private const val TAG = "MainActivity"
        private const val TIME_DAY = 24 * 60 * 60 * 1000


    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val mainActivity = findViewById<ConstraintLayout>(R.id.main_activity)
        val topPadding = getStatusBarHeight(this)
        mainActivity.setPadding(0, topPadding + 10, 0, 0)

        initView()
        initData()
        initListener()

        startFloatingService() // 启动应用就打开浮窗
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initListener() {
        mBtnOpenFloatWindow.setOnClickListener { startFloatingService() }//启动浮窗检测
        mBtnQuitApp.setOnClickListener { ActivityCollector.finishAll() }
        mBtnDropbox.setOnClickListener { selectDateDialog() }
    }

    private fun initData() {}
    private fun initView() {

        mBtnOpenFloatWindow = findViewById(R.id.perfView)
        mBtnQuitApp = findViewById(R.id.quit)
        mBtnDropbox = findViewById(R.id.dropbox)

    }

    /**
     * 启动浮窗
     * 判断是否授权，没授权则跳转到授权界面
     *
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private fun startFloatingService() {
        if (!Settings.canDrawOverlays(this)) {
            PopTipUtils.warnMsg("当前无权限，请授权")
            startActivityForResult(
                Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse(
                        "package:$packageName"
                    )
                ), 0
            ) // 跳转到打开悬浮窗设置页
        } else {
            requestScreenCapturePermission()
        }


    }

    @RequiresApi(Build.VERSION_CODES.O)
    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i(TAG, "onActivityResult: 1")
        if (requestCode == 0) {
            if (!Settings.canDrawOverlays(this)) {
                PopTipUtils.errMsg("授权失败")
            } else {
                PopTipUtils.successMsg("授权成功")
            }
        }
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            val intent = Intent(this@MainActivity, FloatingService::class.java)
            intent.putExtra("code", resultCode)
            intent.putExtra("data", data)
            startForegroundService(intent) // 启动悬浮窗服务
        }
    }


    @SuppressLint("InternalInsetResource", "DiscouragedApi")
    private fun getStatusBarHeight(activity: Activity): Int {
        val resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android")
        return if (resourceId > 0) {
            activity.resources.getDimensionPixelSize(resourceId)
        } else {
            TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                24f, // 默认值，可以根据实际情况修改
                activity.resources.displayMetrics
            ).toInt()
        }
    }

    private fun dropboxLog(time: Long) {
        val handlerThread = HandlerThread("DropboxExporter")
        handlerThread.start()
        val handler = Handler(handlerThread.looper)
        var destPath: String?
        handler.post {
            destPath = DropboxLogcatManager.instance?.output(
                Environment.getExternalStorageDirectory().path + "/sunkit/dropbox.log",
                time,
                800 * 1024
            )
            Log.d("MainActivity", "dropbox output success: $destPath")
            if (destPath == null) {
                runOnUiThread {
                    PopTipUtils.errMsg("dropbox记录的日志信息失败")
                }
            } else {
                PopTipUtils.successMsg("dropbox记录的日志信息保存路径${destPath}")

            }
        }
    }

    private fun selectDateDialog() {
        var selectMenuIndex = 0
        BottomMenu.show(mSingleSelectMenuText as List<CharSequence>?)
            .setTitle("选择抓去日志的开始时间")
            .setOnMenuItemClickListener(object : OnMenuItemSelectListener<BottomMenu>() {
                override fun onOneItemSelect(
                    dialog: BottomMenu?,
                    text: CharSequence?,
                    index: Int,
                    select: Boolean
                ) {
                    selectMenuIndex = index
                }
            })
            .setCancelButton(
                "确定"
            ) { _, _ ->
                dropboxLog(mSingleSelectDay[selectMenuIndex])
                false
            }.selection = selectMenuIndex
    }


    // 请求用户权限
    private fun requestScreenCapturePermission() {
        mediaProjectionManager =
            ContextCompat.getSystemService(this, MediaProjectionManager::class.java)
        startActivityForResult(
            mediaProjectionManager!!.createScreenCaptureIntent(),
            REQUEST_MEDIA_PROJECTION
        )
    }
}
